# 3. 利用本周学习的知识实现如下效果的程序：
#
# 1. server端监听指定的tcp端口
# 2. server端预先实现简单加减法的代码(可以自行扩展其他更复杂功能)
# 3. client端可以通过socket连接与server端通信传输需要参数
# 4. server端根据传的参数计算结果并返回
# 5. client端打印返回结果

# 实现计算客户端

import socket
import sys
import threading
import selectors

class CompClient:
    def __init__(self,addr):
        self.addr = addr
        self.selector = selectors.DefaultSelector()
        self.event = threading.Event()



    def sendandrecv(self, client, mask):
        try:
            data = input("Please input legal calculation formula like 2+3 or 2.01 * 5 or quit!: ")
            self.client.send(data.encode())

            msg = self.client.recv(1024)
            if msg == b'':
                self.client.close()
                self.stop()
                sys.exit()
            print("\nServer response: {}".format(msg.decode()))
        except Exception as e:
            print(e)
    def start(self):
        self.client = socket.socket()
        self.client.connect(self.addr)

        key = self.selector.register(self.client, selectors.EVENT_WRITE | selectors.EVENT_READ, self.sendandrecv)
        threading.Thread(target=self.select, name='select').start()

    def select(self):
        with self.selector:
            while not self.event.is_set():
                events = self.selector.select(0.5)
                for key, mask in events:
                    key.data(key.fileobj, mask)




    def stop(self):
        self.event.set()


while True:
    port = input("please input server's port: ")
    port = int(port)
    if port <1000 or port > 65535:
        print("please input port between 1000 and 65535\n")
    else:
        break


addr = '127.0.0.1', port
cc = CompClient(addr)
cc.start()


